package com.langhua.controller;

import com.langhua.common.R;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.OutputStream;

@RestController
@RequestMapping("/files")
public class FileController {




    @Value("${seatFile.path}")
    private String Path;

    // 文件上传
    @PostMapping("/uploadFile")
    public R save(MultipartFile file){
        //原始文件名称
        String originalFilename = file.getOriginalFilename();  //abc.jpg    abcd.png
        System.out.println("原始文件名称2:"+originalFilename);
        String substring = originalFilename.substring(originalFilename.lastIndexOf("."));  //截取文件名后面的后缀  .jpg/.png

        //随机生成5位数
        Integer num = (int) ((Math.random() * 9 + 1) * 10000);
        String filename = String.valueOf(num)+originalFilename;

        //创建一个目录对象
        File dir =new File(Path);
        //判断当前目录 Path 是否存在
        if (!dir.exists()){
            //目录不存在，需要创建
            dir.mkdirs();
        }

        try {
            //file是一个临时文件，需要将转存到指定位置下，否则本次请求完成后临时文件会删除
            file.transferTo(new File(Path+filename));
        } catch (IOException e) {
            e.printStackTrace();
        }

        return R.success(filename,"上传成功");

    }

    @GetMapping("/downloadFile")
    public void downloadDevtool(String name, HttpServletResponse response) throws IOException {

        File file = new File(name);
        String filename = name.substring(name.lastIndexOf("/")+1);
        response.setContentType("application/x-download");
//        response.setHeader("content-Disposition", "attachment;filename=" + filename);  //这个下载 下载之后的中文变成下划线等乱码

        //设置成浏览器能看懂的编码格式
        response.addHeader("Content-Disposition", "attachment;filename=" + new String(filename.getBytes("utf-8"),"ISO8859-1"));
        FileInputStream fileInputStream = null;

        try {
            fileInputStream = new FileInputStream(new File(Path + name));
            int len = 0;
            byte buffer[] = new byte[1024];
            OutputStream out = response.getOutputStream();
            while ((len = fileInputStream.read(buffer)) > 0) {
                out.write(buffer, 0, len);
            }

        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (fileInputStream != null) {
                try {
                    fileInputStream.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }

        }
    }



}
